<template>
  <div id="comChat">
    <el-container style="height: 100vh; border: 1px">
      <el-header>
        <el-row>
          <el-col :span="2"
            ><div class="grid-content bg-purple">聘途</div></el-col
          >
          <el-col :span="2" :offset="20"
            ><div class="grid-content bg-purple">
              <el-button
                style="font-size: large; color: black"
                type="text"
                @click="Loginout"
                >退出登录</el-button
              >
            </div></el-col
          >
        </el-row>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <Sidebar></Sidebar>
        </el-aside>
        <el-main class="el-main1">
          <el-container class="chat-area">
            <!-- 顶部 -->
            <el-header>
              <el-row>
                <el-col :span="4"
                  ><div
                    class="grid-content bg-purple"
                    style="font-size: x-large"
                  >
                    {{ username }}
                  </div></el-col
                >
                <el-col :span="18"
                  ><div
                    class="grid-content bg-purple-light"
                    style="font-size: x-large; color: aqua"
                  >
                    <div v-if="chatMes">正在与{{ toName }}聊天</div>
                    <div v-else style="height: 40px">&nbsp;</div>
                    <!-- 占位符 -->
                  </div>
                </el-col>
                <el-col :span="2"
                  ><div>
                    <div
                      class="grid-content bg-purple"
                      style="font-size: x-large; color: green"
                      v-if="isOnline"
                    >
                      在线
                    </div>
                    <div
                      class="grid-content bg-purple"
                      style="font-size: x-large; color: red"
                      v-else
                    >
                      离线
                    </div>
                  </div></el-col
                >
              </el-row>
            </el-header>
            <!-- 主体 -->
            <el-main class="el-main2">
              <!-- 主体 -->
              <div class="chat-area-body">
                <el-container>
                  <!-- 左侧 -->
                  <el-aside width="70%" class="chat-area-body-left">
                    <!-- 用户聊天区 -->
                    <div class="chat-area-body-left-chatarea">
                      <div
                        class="chatarea-list"
                        v-for="mess in historyMessage"
                        :key="mess"
                      >
                        <!-- 左侧 -->
                        <div v-if="mess.fromName">
                          <!-- 名称 -->
                          <div style="height: 30px">
                            <span style="float: left">{{ toName }}</span>
                          </div>
                          <div
                            style="
                              display: flex;
                              justify-content: flex-start;
                              overflow: hidden;
                            "
                          >
                            <!-- 头像 -->
                            <div>
                              <img
                                src="..\public\Member002.jpg"
                                alt=""
                                style="float: left"
                              />
                            </div>
                            <!-- 内容 -->
                            <div class="chat-area-elearea">
                              <p style="float: left">{{ mess.message }}</p>
                            </div>
                          </div>
                        </div>
                        <!-- 右侧 -->
                        <div v-else>
                          <!-- 名称 -->
                          <div style="height: 30px">
                            <span style="float: right">{{ username }}</span>
                          </div>
                          <div
                            style="
                              display: flex;
                              justify-content: flex-end;
                              overflow: hidden;
                            "
                          >
                            <!-- 内容 -->
                            <div class="chat-area-elearea">
                              <p style="float: right">{{ mess.message }}</p>
                            </div>
                            <!-- 头像 -->
                            <div>
                              <img
                                src="..\public\Member001.jpg"
                                alt=""
                                style="float: right"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- 发送文本区 -->
                    <div class="chat-area-body-left-submit">
                      <div class="chat-area-body-left-submit-textarea">
                        <textarea
                          class="scroll"
                          id="context_text"
                          @keyup.enter="submit"
                          placeholder="在此输入文字信息..."
                          v-model="sendMessage.message"
                        >
                        </textarea>
                      </div>
                      <el-button
                        type="primary"
                        class="chat-area-body-left-submit-bt"
                        @click="submit"
                        >发送</el-button
                      >
                    </div>
                  </el-aside>
                  <!-- 右侧 -->
                  <el-main class="chat-area-body-right">
                    <!-- 用户列表 -->
                    <div class="chat-area-body-right-list-head">用户列表</div>
                    <div class="chat-area-body-right-list">
                      <ul class="user-list">
                        <li
                          class="user-list-ele"
                          v-for="friend in friendsList"
                          :key="friend.id"
                        >
                          <a @click="showChat(friend)">{{ friend }}</a>
                        </li>
                      </ul>
                    </div>
                    <!-- 广播区 -->
                    <div class="chat-area-body-right-broadcast-head">
                      系统广播
                    </div>
                    <div class="chat-area-body-right-broadcast">
                      <ul class="user-list">
                        <li
                          class="user-list-ele"
                          v-for="friend in friendsList"
                          :key="friend"
                        >
                          <a>{{ friend }} 已上线</a>
                        </li>
                      </ul>
                    </div>
                  </el-main>
                </el-container>
              </div>
            </el-main>
          </el-container>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>


<script>
import axios from "axios";
import Sidebar from "@/components/CompanySidebar.vue";
import { EventBus } from '@/util/event-bus.js';
export default {
  components: {
    Sidebar,
  },
  created() {
    this.username = this.CompanyUserData.cname;
    this.createWebSocket();
    EventBus.$on('close-websocket-company', () => {
      this.closeWebSocket();
    });
  },
  data() {
    return {
      CompanyUserData: JSON.parse(sessionStorage.getItem("CompanyUser")),
      username: "",
      webSocket: null,
      isOnline: true,
      chatMes: false, //正在与谁聊天的布尔值
      toName: "",
      friendsList: [],
      sendMessage: {
        toName: "",
        message: "",
      },
      historyMessage: [], //String fromName, Object message
      ano_historyMessage: [], //辅助数组
    };
  },
  methods: {
    Loginout(){
      this.closeWebSocket();
      let data = new FormData();
      data.append("cusername", this.CompanyUserData.cusername);
      axios
        .post("http://localhost:8080/hqdx/company/loginout", data)
        .then((response) => {})
        .catch((error) => {
          console.log(error);
        });
      this.$router.push('/login');
      sessionStorage.setItem('LoginComState', JSON.stringify(false));//退出登录，状态记录
    },
    showChat(name) {
      this.toName = name;
      // 清除聊天区的数据，展示新聊天区的数据
      let history = sessionStorage.getItem(this.toName);
      if (!history) {
        this.historyMessage = [];
      } else {
        this.historyMessage = JSON.parse(history);
      }
      this.chatMes = true; //正在与谁聊天的布尔值
    },
    submit() {
      this.sendMessage.message = this.sendMessage.message.trim(); //去除空白字符
      if (!this.sendMessage.message) {
        alert("请输入内容");
        return;
      }
      if (!this.toName) {
        alert("没有聊天对象");
        return;
      }
      this.sendMessage.toName = this.toName;
      this.historyMessage.push(JSON.parse(JSON.stringify(this.sendMessage))); //toName,message
      sessionStorage.setItem(this.toName, JSON.stringify(this.historyMessage)); //存储与每个相关的聊天数据
      this.webSocket.send(JSON.stringify(this.sendMessage));
      this.sendMessage.message = "";
    },
    createWebSocket() {
      // 创建 WebSocket 连接到 'ws://localhost:7024/chat'
      this.webSocket = new WebSocket("ws://localhost:8080/hqdx/chat");
      this.webSocket.onopen = this.onOpen;
      this.webSocket.onmessage = this.onMessage;
      this.webSocket.onclose = this.onClose;
    },
    onOpen: function (event) {
      // WebSocket 连接打开时触发
      this.isOnline = true;
      console.log("WebSocket 连接打开");
    },
    onMessage: function (event) {
      // 获取服务端推送过来的消息
      let dataString = event.data;
      // 将 dataString 转换为 json 对象
      let response = JSON.parse(dataString);

      console.log("服务端推送过来的消息：", response);
      // 判断是否是系统消息
      if (response.system) {
        // 系统消息 好友列表展示
        let names = response.message;
        //好友列表
        //清空原始用户列表
        this.friendsList = [];
        for (let i = 0; i < names.length; i++) {
          if (names[i] !== this.username) {
            console.log("本名：" + this.username, "加入的姓名" + names[i]);
            this.friendsList.push(names[i]);
          }
        }
      } else {
        // 非系统消息
        // console.log(this.username,"与",response.fromName,"存储的内容：",sessionStorage.getItem(response.fromName));
        //找与发送者的往期记录
        let history=JSON.parse(sessionStorage.getItem(response.fromName));
        if (history !== null) {
          this.ano_historyMessage = history;
        }
        console.log("类型:", typeof this.ano_historyMessage, "值:", this.ano_historyMessage);
        this.ano_historyMessage.push(response);
        sessionStorage.setItem(
          response.fromName,
          JSON.stringify(this.ano_historyMessage)
        );
        //如果是当前聊天页面，就更新
        if (this.toName === response.fromName) {
          this.historyMessage.push(response);
        }
        this.ano_historyMessage = [];
      }
    },
    onClose: function (event) {
      // WebSocket 连接关闭时触发
      this.isOnline = false;
      console.log("WebSocket 连接关闭", event);
    },
    closeWebSocket() {
      if (this.webSocket) {
        this.webSocket.close();
      }
    },
  },
  beforeDestroy() {
    EventBus.$off('close-websocket-company', this.closeWebSocket);
  },
};
</script>

  
  <style scoped>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
}

.el-main1{
  background: linear-gradient(to bottom, #ffffff, #e0f7fa);
  /* background-color: #e9eef3; */
  color: #333;
}

/* 不清楚作用 */
body > .el-container {
  margin-bottom: 40px;
}
.el-header {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
  height: 65px;
}
.chat-area {
  margin-left: 10%;
  margin-top: 20px;
  height: 800px;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  border-bottom: 1px solid #000;
  width: 70%;
}
.el-main2 {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  padding: 0;
  overflow:auto;
}
.chat-area-body-left {
  background-color: white;
  color: #333;
  /* text-align: center; */
  /* line-height: 200px; */
  height: 735px;
  border-right: 1px solid #000;
  overflow: hidden;
}
.chat-area-body-right {
  background-color: white;
  color: #333;
  text-align: center;
  /* line-height: 160px; */
  height: 735px;
  padding: 0px;
  overflow: hidden;
}
.chat-area-body-left-chatarea {
  background-color: white;
  /* text-align: center; */
  height: 485px;
  width: 100%;
  overflow: auto;
}
.chat-area-body-left-submit {
  background-color: white;
  /* text-align: center; */
  height: 230px;
  width: 100%;
  border-top: 1px solid #000;
}
.chat-area-body-right-list {
  background-color: white;
  text-align: center;
  height: 300px;
  width: 100%;
  overflow: auto;
}
.chat-area-body-right-broadcast {
  background-color: white;
  text-align: center;
  height: 535px;
  width: 100%;
  /* border-top: 1px solid #000; */
  overflow: auto;
}
.scroll {
  width: 99%;
  height: 180px;
  resize: none;
  overflow-x: hidden; /* 防止文本溢出 */
  overflow-y: auto; /* 允许文本滚动 */
  border: none; /* 取消边框 */
  font-size: xx-large;
}
.scroll:focus {
  outline: none; /* 或者你可以设置一个 outline 样式来提供焦点反馈 */
}
.chat-area-body-left-submit-bt {
  float: right;
  margin-right: 20px;
}
.chat-area-body-right-broadcast-head {
  color: #51b1d9;
  border-bottom: 1px solid #000;
  width: 100%;
  font-size: x-large;
  float: left;
  padding-bottom: 10px;
}
.chat-area-body-right-list-head {
  color: #51b1d9;
  border-bottom: 1px solid #000;
  width: 100%;
  font-size: x-large;
  float: left;
  padding-bottom: 10px;
}
.user-list {
  margin: 0;
  text-align: left;
  list-style: none;
  padding-right: 0.5em;
  color: #000;
  overflow: auto;
  bottom: 0.1em;
  padding-left: 1.5em;
}
.user-list-ele {
  margin: 0.5em 0;
  position: relative;
  counter-increment: rel;
  line-height: 1.5em;
  cursor: pointer;
}
.user-list-ele:hover {
  opacity: 0.6;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)";
  filter: alpha(opacity=60);
}
.chatarea-list {
  display: flex;
  flex-direction: column;
}
.chat-area-elearea {
  max-width: 70%;
  margin-right: 10px;
  margin-left: 10px;
  background-color: #f0f0f0;
  border-radius: 15px;
  font-size: large;
}
.chat-area-body {
  height: 735px;
}
</style>